﻿#include "QCefDebug.h"


#define LOG_MSG_BUFFER_LIMIT 4092


enum log_level
{
    log_debug = 0,
    log_warn,
    log_error,   // = log_critical
    log_fatal,
    log_info,
};


size_t qcef_header(log_level level, char * buf)
{
    time_t cur;
    ::time(&cur);

    tm tmCur;
    ::localtime_s(&tmCur, &cur);

    size_t index = 0;

    switch (level)
    {
    case log_debug:
        index = ::strftime(buf, 32, "%Y-%m-%d %H:%M:%S d ", &tmCur);
        break;
    case log_warn:
        index = ::strftime(buf, 32, "%Y-%m-%d %H:%M:%S w ", &tmCur);
        break;
    case log_error:
        index = ::strftime(buf, 32, "%Y-%m-%d %H:%M:%S e ", &tmCur);
        break;
    case log_fatal:
        index = ::strftime(buf, 32, "%Y-%m-%d %H:%M:%S f ", &tmCur);
        break;
    case log_info:
        index = ::strftime(buf, 32, "%Y-%m-%d %H:%M:%S i ", &tmCur);
        break;
    default:
        index = ::strftime(buf, 32, "%Y-%m-%d %H:%M:%S u ", &tmCur);
        break;
    }

    return index;
}

void qcef_debug(const char* fmt, ...)
{
    std::vector<char> msg(LOG_MSG_BUFFER_LIMIT+4, 0);

    size_t index = qcef_header(log_debug, msg.data());

    va_list args;
    va_start(args, fmt);
    vsnprintf(msg.data() + index, LOG_MSG_BUFFER_LIMIT - index, fmt, args);
    va_end(args);

    ::OutputDebugStringA(msg.data());
}

void qcef_warn(const char* fmt, ...)
{
    std::vector<char> msg(LOG_MSG_BUFFER_LIMIT+4, 0);

    size_t index = qcef_header(log_warn, msg.data());

    va_list args;
    va_start(args, fmt);
    vsnprintf(msg.data() + index, LOG_MSG_BUFFER_LIMIT - index, fmt, args);
    va_end(args);

    ::OutputDebugStringA(msg.data());
}

void qcef_error(const char* fmt, ...)
{
    std::vector<char> msg(LOG_MSG_BUFFER_LIMIT+4, 0);

    size_t index = qcef_header(log_error, msg.data());

    va_list args;
    va_start(args, fmt);
    vsnprintf(msg.data() + index, LOG_MSG_BUFFER_LIMIT - index, fmt, args);
    va_end(args);

    ::OutputDebugStringA(msg.data());
}

void qcef_fatal(const char* fmt, ...)
{
    std::vector<char> msg(LOG_MSG_BUFFER_LIMIT+4, 0);

    size_t index = qcef_header(log_fatal, msg.data());

    va_list args;
    va_start(args, fmt);
    vsnprintf(msg.data() + index, LOG_MSG_BUFFER_LIMIT - index, fmt, args);
    va_end(args);

    ::OutputDebugStringA(msg.data());
}


void qcef_info(const char* fmt, ...)
{
    std::vector<char> msg(LOG_MSG_BUFFER_LIMIT+4, 0);

    size_t index = qcef_header(log_info, msg.data());

    va_list args;
    va_start(args, fmt);
    vsnprintf(msg.data() + index, LOG_MSG_BUFFER_LIMIT - index, fmt, args);
    va_end(args);

    ::OutputDebugStringA(msg.data());
}
